import os
import requests
import time
from urllib.parse import urlparse

class AssetDownloader:
    def __init__(self):
        # 基础路径
        self.static_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'app/static')
        self.css_dir = os.path.join(self.static_dir, 'css')
        self.js_dir = os.path.join(self.static_dir, 'js')
        
        # 超时设置
        self.timeout = 10
        
        # 使用 BootCDN
        self.files = {
            'css': {
                # Bootstrap
                'bootstrap.min.css': 'https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.2/css/bootstrap.min.css',
                # DataTables
                'dataTables.bootstrap5.min.css': 'https://cdn.bootcdn.net/ajax/libs/datatables/1.13.6/css/dataTables.bootstrap5.min.css',
            },
            'js': {
                # jQuery
                'jquery.min.js': 'https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js',
                # Bootstrap
                'bootstrap.bundle.min.js': 'https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.2/js/bootstrap.bundle.min.js',
                # DataTables
                'jquery.dataTables.min.js': 'https://cdn.bootcdn.net/ajax/libs/datatables/1.13.6/js/jquery.dataTables.min.js',
                'dataTables.bootstrap5.min.js': 'https://cdn.bootcdn.net/ajax/libs/datatables/1.13.6/js/dataTables.bootstrap5.min.js',
                # Chart.js
                'chart.min.js': 'https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.0/chart.umd.min.js',
            }
        }

    def ensure_directories(self):
        """确保目录存在"""
        os.makedirs(self.css_dir, exist_ok=True)
        os.makedirs(self.js_dir, exist_ok=True)

    def download_file(self, url, save_path):
        """下载单个文件"""
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        
        try:
            response = requests.get(url, headers=headers, timeout=self.timeout)
            response.raise_for_status()
            
            with open(save_path, 'wb') as f:
                f.write(response.content)
            print(f"成功下载: {save_path}")
            return True
            
        except requests.RequestException as e:
            print(f"下载失败 {url}: {str(e)}")
            return False

    def download_all(self):
        """下载所有文件"""
        self.ensure_directories()
        
        # 先删除所有现有文件
        for dir_path in [self.css_dir, self.js_dir]:
            if os.path.exists(dir_path):
                for file in os.listdir(dir_path):
                    file_path = os.path.join(dir_path, file)
                    try:
                        os.remove(file_path)
                        print(f"删除旧文件: {file_path}")
                    except OSError as e:
                        print(f"无法删除文件 {file_path}: {e}")
        
        for file_type, files in self.files.items():
            base_dir = self.css_dir if file_type == 'css' else self.js_dir
            
            for filename, url in files.items():
                save_path = os.path.join(base_dir, filename)
                
                # 尝试下载3次
                for attempt in range(3):
                    if self.download_file(url, save_path):
                        break
                    print(f"重试 {attempt + 1}/3: {filename}")
                    time.sleep(2)

    def create_custom_css(self):
        """创建自定义CSS文件"""
        custom_css = """
/* 自定义样式 */
:root {
    --primary-color: #2c3e50;
    --secondary-color: #34495e;
}

/* 暗色模式 */
body.dark-mode {
    background-color: #1a1a1a;
    color: #f0f0f0;
}

body.dark-mode .navbar {
    background-color: #2c2c2c !important;
    border-bottom: 1px solid #3c3c3c !important;
}

body.dark-mode .navbar-light .navbar-brand,
body.dark-mode .navbar-light .nav-link {
    color: #f0f0f0;
}

body.dark-mode .card {
    background-color: #2c2c2c;
    border-color: #3c3c3c;
}

body.dark-mode .bg-light {
    background-color: #2c2c2c !important;
}

body.dark-mode .text-muted {
    color: #a0a0a0 !important;
}
"""
        with open(os.path.join(self.css_dir, 'custom.css'), 'w', encoding='utf-8') as f:
            f.write(custom_css)

if __name__ == '__main__':
    downloader = AssetDownloader()
    downloader.download_all()
    downloader.create_custom_css() 